package com.ruoyi.asset.service.impl;

import java.util.List;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.asset.mapper.TAssetMapper;
import com.ruoyi.asset.domain.TAsset;
import com.ruoyi.asset.domain.AssetStatistics;
import com.ruoyi.asset.service.ITAssetService;
import com.ruoyi.system.service.IImageCleanupService;
import com.ruoyi.common.utils.SecurityUtils;
import com.alibaba.fastjson2.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 资产Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-09-24
 */
@Service
public class TAssetServiceImpl implements ITAssetService 
{
    private static final Logger log = LoggerFactory.getLogger(TAssetServiceImpl.class);

    @Autowired
    private TAssetMapper tAssetMapper;

    @Autowired
    private IImageCleanupService imageCleanupService;

    /**
     * 查询资产
     * 
     * @param assetNo 资产主键
     * @return 资产
     */
    @Override
    public TAsset selectTAssetByAssetNo(String assetNo)
    {
        return tAssetMapper.selectTAssetByAssetNo(assetNo);
    }

    /**
     * 查询资产列表
     * 
     * @param tAsset 资产
     * @return 资产
     */
    @Override
    public List<TAsset> selectTAssetList(TAsset tAsset)
    {
        return tAssetMapper.selectTAssetList(tAsset);
    }

    /**
     * 新增资产
     * 
     * @param tAsset 资产
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertTAsset(TAsset tAsset)
    {
        // 设置创建时间
        tAsset.setCreatedAt(new Date());
        tAsset.setUpdatedAt(new Date());
        
        int result = tAssetMapper.insertTAsset(tAsset);
        
        // 记录图片关联关系
        if (result > 0 && tAsset.getImageUrls() != null && !tAsset.getImageUrls().isEmpty()) {
            recordAssetImages(tAsset.getAssetNo(), tAsset.getImageUrls());
        }
        
        return result;
    }

    /**
     * 修改资产
     * 
     * @param tAsset 资产
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateTAsset(TAsset tAsset)
    {
        // 获取旧资产信息
        TAsset oldAsset = tAssetMapper.selectTAssetByAssetNo(tAsset.getAssetNo());
        
        // 设置更新时间
        tAsset.setUpdatedAt(new Date());
        
        int result = tAssetMapper.updateTAsset(tAsset);
        
        // 处理图片关联关系
        if (result > 0) {
            updateAssetImages(tAsset.getAssetNo(), oldAsset, tAsset);
        }
        
        return result;
    }

    /**
     * 批量删除资产
     * 
     * @param assetNos 需要删除的资产主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteTAssetByAssetNos(String[] assetNos)
    {
        // 删除资产关联的图片
        for (String assetNo : assetNos) {
            try {
                imageCleanupService.deleteBusinessImages("asset", assetNo, "images");
                log.info("删除资产 {} 关联的图片", assetNo);
            } catch (Exception e) {
                log.error("删除资产 {} 关联的图片失败: {}", assetNo, e.getMessage());
            }
        }
        
        return tAssetMapper.deleteTAssetByAssetNos(assetNos);
    }

    /**
     * 删除资产信息
     * 
     * @param assetNo 资产主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteTAssetByAssetNo(String assetNo)
    {
        // 删除资产关联的图片
        try {
            imageCleanupService.deleteBusinessImages("asset", assetNo, "images");
            log.info("删除资产 {} 关联的图片", assetNo);
        } catch (Exception e) {
            log.error("删除资产 {} 关联的图片失败: {}", assetNo, e.getMessage());
        }
        
        return tAssetMapper.deleteTAssetByAssetNo(assetNo);
    }

    /**
     * 记录资产图片关联关系
     */
    private void recordAssetImages(String assetNo, String imageUrlsJson) {
        try {
            List<String> imageUrls = JSON.parseArray(imageUrlsJson, String.class);
            Long userId = SecurityUtils.getUserId();
            
            for (String imageUrl : imageUrls) {
                if (imageUrl != null && !imageUrl.isEmpty()) {
                    // 从URL中提取文件名
                    String fileName = extractFileNameFromUrl(imageUrl);
                    if (fileName != null) {
                        imageCleanupService.recordImageAttachment(
                            fileName, "asset", assetNo, "images", userId
                        );
                        log.info("记录资产图片关联: {} -> {}", fileName, assetNo);
                    }
                }
            }
        } catch (Exception e) {
            log.error("记录资产图片关联失败: {}", e.getMessage(), e);
        }
    }

    /**
     * 更新资产图片关联关系
     */
    private void updateAssetImages(String assetNo, TAsset oldAsset, TAsset newAsset) {
        try {
            String oldImageUrls = oldAsset != null ? oldAsset.getImageUrls() : null;
            String newImageUrls = newAsset.getImageUrls();
            
            // 如果图片没有变化，直接返回
            if (oldImageUrls != null && oldImageUrls.equals(newImageUrls)) {
                return;
            }
            
            Long userId = SecurityUtils.getUserId();
            
            // 处理旧图片
            if (oldImageUrls != null && !oldImageUrls.isEmpty()) {
                List<String> oldUrls = JSON.parseArray(oldImageUrls, String.class);
                for (String oldUrl : oldUrls) {
                    if (oldUrl != null && !oldUrl.isEmpty()) {
                        String oldFileName = extractFileNameFromUrl(oldUrl);
                        if (oldFileName != null) {
                            imageCleanupService.updateImageAttachment(
                                oldFileName, null, "asset", assetNo, "images", userId
                            );
                        }
                    }
                }
            }
            
            // 处理新图片
            if (newImageUrls != null && !newImageUrls.isEmpty()) {
                recordAssetImages(assetNo, newImageUrls);
            }
            
        } catch (Exception e) {
            log.error("更新资产图片关联失败: {}", e.getMessage(), e);
        }
    }

    /**
     * 从URL中提取文件名
     */
    private String extractFileNameFromUrl(String url) {
        if (url == null || url.isEmpty()) {
            return null;
        }
        
        try {
            // 如果是完整的URL，提取文件名部分
            if (url.contains("/")) {
                return url.substring(url.lastIndexOf("/") + 1);
            }
            // 如果直接是文件名，直接返回
            return url;
        } catch (Exception e) {
            log.error("提取文件名失败: {}", url, e);
            return null;
        }
    }

    /**
     * 查询资产维修历史
     * 
     * @param assetNo 资产编号
     * @param startDate 开始日期
     * @param endDate 结束日期
     * @return 维修历史列表
     */
    @Override
    public List<TAsset> selectAssetRepairHistory(String assetNo, String startDate, String endDate)
    {
        return tAssetMapper.selectAssetRepairHistory(assetNo, startDate, endDate);
    }

    /**
     * 获取资产统计信息
     * 
     * @return 资产统计数据
     */
    @Override
    public AssetStatistics getAssetStatistics()
    {
        // 查询总设备数
        Long total = tAssetMapper.countTotalAssets();
        
        // 查询各状态设备数
        Long normal = tAssetMapper.countAssetsByStatus("ASSET_STATUS_001"); // 正常
        Long fault = tAssetMapper.countAssetsByStatus("ASSET_STATUS_002"); // 故障
        Long idle = tAssetMapper.countAssetsByStatus("ASSET_STATUS_003"); // 闲置
        Long scrapped = tAssetMapper.countAssetsByStatus("ASSET_STATUS_004"); // 已报废
        Long maintenance = tAssetMapper.countAssetsByStatus("ASSET_STATUS_005"); // 维护中
        
        return new AssetStatistics(total, normal, fault, idle, scrapped, maintenance);
    }
}